package com.yiyiooo.Abp.basics;

import android.content.Context;
import android.content.SharedPreferences;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.yiyiooo.Abp.AppBootstrap;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 *  本地存储
 * */
public class LocalStore {
//    private static Map<String,String> store = Collections.synchronizedMap(new HashMap<String,String>(){});
    private static Map<String,String> store = new HashMap<String,String>(){};
    private static boolean hasLoad = false;
    private static String sharedPreferencesName = "abpStore";

    private  LocalStore(){
        sp = AppBootstrap.getAppContext().getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE);
    }
    private static LocalStore localStore = new LocalStore();
    public static LocalStore getInstance(){
        return localStore;
    }
    SharedPreferences sp;
    private void load(){
        if(hasLoad) return;
        for(String key:sp.getAll().keySet()){
            store.put(key,sp.getString(key,""));
        }
        hasLoad = true;
    }
    private void save(){
        SharedPreferences.Editor editor = sp.edit();
        for(String key:store.keySet()){
            editor.putString(key, store.get(key));
        }
        editor.apply();
        hasLoad = false;
    }

    /**
     * 获取本地存储的值
     * @param key 唯一键
     * @return 字符串
     */
    public String getStore(String key){
        load();
        return store.get(key);
    }


    /**
     * 获取本地存储的json字符串
     * @param key 唯一键
     * @return json对象
     */
    public JSONObject getJson(String key){
        try {
            return JSON.parseObject(getStore(key));
        }catch (JSONException ex){
            return null;
        }
    }

    /**
     * 将字符串写入本地存储
     * @param key 唯一键
     * @param value 值（字符串）
     */
    public void setStore(String key,String value){
        boolean hSave = !Objects.equals(store.get(key), value);
        store.put(key,value);
        if(hSave) save();
    }

    /**
     * 将json字符串写入本地存储
     * @param key 唯一键
     * @param json json对象
     */
    public void setStoreAsJson(String key,JSONObject json){
        setStore(key,json.toJSONString());
    }
}
